﻿using OAuth2Authorizer.Framework;
using OAuth2Authorizer.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;

namespace OAuth2Authorizer.Google
{
    internal class GoogleAuthorizer : AuthorizerBase, IAuthorizer
    {
        private static readonly string AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth";
        private static readonly string AuthorizeUrlTemplate = "{0}?&response_type={1}&redirect_uri={2}&client_id={3}";
        private static readonly string TokenUrl = "https://accounts.google.com/o/oauth2/token";
        private static readonly string AuthType = "code";
        private static readonly string GrantTypeValue = "authorization_code";
        

        public GoogleAuthorizer() : base(TokenUrl) 
        {
        }

        protected override string GetAuthorizeUrlInternal(string appKey, string redirectUrl, string state)
        {
            return string.Format(AuthorizeUrlTemplate, AuthorizeUrl, AuthType, redirectUrl, appKey);
        }

        protected override NameValueCollection GetTokenRequestParameters(string appKey, string appSecret, string redirectUrl, string code)
        {
            var parameters = new NameValueCollection();
            parameters.Add("grant_type", GrantTypeValue);
            parameters.Add("client_id", appKey);
            parameters.Add("client_secret", appSecret);
            parameters.Add("code", code);
            parameters.Add("redirect_uri", redirectUrl);
            return parameters;
        }

        protected override AccessTokenResponse GetResponseObject(Stream stream, string contentType)
        {
            var serializer = SerializerFactory.CreateSerializer<GoogleAccessToken>(contentType);
            var token = serializer.ReadObject(stream);
            return token.AsAccessTokenResponse();
        }
    }
}
